using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using JVIT.TimeSheet.BLL;

namespace JVIT.TimeSheet.GUI
{
    public partial class PauseDetail : Form
    {
        private Pause Pause { get; set; }
        private DateTime WorkDate { get; set; }

        public PauseDetail(Pause pause)
        {
            InitializeComponent();
            this.Pause = pause;
            this.WorkDate = pause.Started == null || pause.Started.Value == null ? DateTime.Now : pause.Started.Value;
            Bind();
        }
        private void Bind()
        {
            txtFrom.Text = this.Pause.Started.ToReadableString();
            txtTo.Text = this.Pause.Ended.ToReadableString();
        }
        private void Save()
        {
            this.Pause.Started = GetDateTimeFromTimeString(txtFrom.Text);
            this.Pause.Ended = GetDateTimeFromTimeString(txtTo.Text);
        }
        private new List<string> Validate()
        {
            List<string> result = new List<string>();
            if (GetDateTimeFromTimeString(txtFrom.Text) == null)
                result.Add("Valid From time mandatory");
            if (string.IsNullOrEmpty(txtTo.Text) == false && GetDateTimeFromTimeString(txtTo.Text) != null && GetDateTimeFromTimeString(txtFrom.Text) != null && GetDateTimeFromTimeString(txtTo.Text) <= GetDateTimeFromTimeString(txtFrom.Text))
                result.Add("End time should be after Start time");
            return result;
        }
        private bool HandleValidation()
        {
            List<string> validationResult = Validate();
            if (validationResult.Count > 0)
            {
                MessageBox.Show(string.Join(Environment.NewLine, validationResult.ToArray()));
                return false;
            }
            return true;
        }
        private DateTime? GetDateTimeFromTimeString(string value)
        {
            DateTime? result = null;
            if (string.IsNullOrEmpty(value) == false)
            {
                try
                {
                    string[] timeParts = value.Split(':');
                    result = new DateTime(this.WorkDate.Year, this.WorkDate.Month, this.WorkDate.Day, int.Parse(timeParts[0]), int.Parse(timeParts[1]), int.Parse(timeParts[2]));
                }
                catch { }
            }
            return result;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (HandleValidation())
            {
                Save();
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
    }
}
